package chpt11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
	public static void main(String[] args) {
		int port = 9000;
		// 创建ServerSocket并监听9000端口
		try (ServerSocket server = new ServerSocket(port)) {
			while (true) {// 等待客户端连接
				try (Socket socket = server.accept();
						// 获取输入流，用于接收客户端发送的消息
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(socket.getInputStream()));
						// 获取输出流，用于向客户端发送消息
						PrintWriter writer = new PrintWriter(
								socket.getOutputStream());) {
					while (true) {
						// 接受客户端的消息
						String line = reader.readLine();
						if (line.equals("bye")) {
							break;
						}
						// 向客户端发送消息
						writer.println(line);
						writer.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
